package com.gopay.bis.service.bank.impl.bcdl;

import java.util.Map;

import javax.annotation.Resource;

import com.gopay.common.domain.bank.ccb.bcdl.querydcc.res.TransResQueryBody6WY101;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.bis.common.util.SendSmsUtils;
import com.gopay.bis.manager.bank.bcdl.CcbBcdlManager;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.CcbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BcdlMessage;
import com.gopay.common.domain.bank.BcdlResult;
import com.gopay.common.domain.bank.bcdl.BcdlPacket;
import com.gopay.common.domain.bank.bcdl.BcdlPacketRes;
import com.gopay.common.domain.bank.ccb.bcdl.corp.res.TransResCorpBody;
import com.gopay.common.domain.bank.ccb.bcdl.person.res.TransResPersonBody;
import com.gopay.common.domain.bank.ccb.bcdl.query.res.TransResQueryBody;
import com.gopay.common.domain.bank.ccb.bcdl.querybalance.res.TransResQueryBalanceBody;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BcdlInteractRemoteService;

public class CcbBcdlServiceImpl extends BaseBcdlServiceImpl implements BcdlInteractRemoteService {
	
	private static Logger logger = LoggerFactory.getLogger(CcbBcdlServiceImpl.class);
	
	@Resource(name = "ccbBcdlManager")
	private CcbBcdlManager ccbBcdlManager;
	@Resource(name = "smsConfig")
	private Map<String, String> smsConfig;

	@Override
	public BcdlResult eft(BcdlMessage base) {
		// TODO Auto-generated method stub
		BcdlResult result = new BcdlResult();
		try {
			BcdlMessage message = (BcdlMessage) base;
			if (message.getDcblType() == BankConstants.DCBL_CORP) {
				TransResCorpBody res = ccbBcdlManager.payCorp(message);
				result.setDefaultModel(res);
				String resultCode = res.getReturnCode()==null?"":res.getReturnCode();
                if (CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)
                        || resultCode.endsWith(CcbConstants.BCDL_RESULT_CODE_UNKNOWN)
                        || CcbConstants.BCDL_RESULT_CODE_ORDER_ERROR.equals(resultCode)
                        || "WLPT_Err1015".equals(resultCode)){
                	result.setBankRetCode(resultCode);
                	result.setErrorMsg(res.getReturnMsg());
					// 交易处理中，需要后续对单时确认是否成功
                    // 防止重复付款，订单号重复报错置为进行中等待人工处理 update 20170516
                	// 紧急修改，增加建行银企直连付款结果code判断，WLPT_Err1015连接服务器失败(12152)（如果该笔交易为帐务交易，则处理结果不确定，请先核对明细！）
	            	result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
	            	result.setSuccess(true);
				} else {
					//modified by zyt,2018-1-25，“是否做拒绝账务”为唯一判断失败的标准，其余非成功的均置进行中
					boolean isNeedRefund = isNeedRefund(res, base.getOrderId());
					result.setNeedRefund(isNeedRefund);
					if(isNeedRefund) {
						result.setBankRetCode(resultCode);
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
						result.setErrorMsg(res.getReturnMsg());
						result.setSuccess(false);
					} else {
						result.setBankRetCode(resultCode);
						result.setErrorMsg(res.getReturnMsg());
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
						result.setSuccess(true);
					}
	    		}
			} else if (message.getDcblType() == BankConstants.DCBL_PERSON) {
				TransResPersonBody res = ccbBcdlManager.payPerson(message);
				result.setDefaultModel(res);
				String resultCode = res.getReturnCode()==null?"":res.getReturnCode();
                if (CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)
                        || CcbConstants.BCDL_RESULT_CODE_ORDER_ERROR.equals(resultCode)
                        || "WLPT_Err1015".equals(resultCode)){
                	result.setBankRetCode(resultCode);
                	result.setErrorMsg(res.getReturnMsg());
					// 交易处理中，需要后续对单时确认是否成功
                    // 防止重复付款，订单号重复报错置为进行中等待人工处理 update 20170516
                	// 紧急修改，增加建行银企直连付款结果code判断，WLPT_Err1015连接服务器失败(12152)（如果该笔交易为帐务交易，则处理结果不确定，请先核对明细！）
	            	result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
	            	result.setSuccess(true);
				} else {
					//modified by zyt,2018-1-25，“是否做拒绝账务”为唯一判断失败的标准，其余非成功的均置进行中
					boolean isNeedRefund = isNeedRefund(res, base.getOrderId());
					result.setNeedRefund(isNeedRefund);
					if(isNeedRefund) {
						result.setBankRetCode(resultCode);
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
						result.setErrorMsg(res.getReturnMsg());
						result.setSuccess(false);
					} else {
						result.setBankRetCode(resultCode);
						result.setErrorMsg(res.getReturnMsg());
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
						result.setSuccess(true);
					}
	    		}
			} else {
                result.setResultCode("CcbBcdlServiceImpl.process:not match");
                return result;
            }
			
		} catch (GopayException e){
			if(ProcCodeConstants.PROC_CODE_100E6047.equals(e.getErrCode())){
				String custName = getCustName(base.getOrderId());
				SendSmsUtils.sendSms(base.getGopayBankOrderNo(), smsConfig.get("switch"), "CCB",smsConfig.get("mobile"),e.getErrMsg()
						+"，商户名称："+custName+",金额："+base.getAmount().toString());
			}
			logger.error("CCB银企直连异常 eft", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("CCB银企直连异常 eft error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public BcdlResult sendBank(BcdlMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BcdlResult query(BcdlMessage base) {
		// TODO Auto-generated method stub
		BcdlResult result = new BcdlResult();
		try {
			BcdlMessage message = (BcdlMessage) base;
			TransResQueryBody res = ccbBcdlManager.payQuery(message);
			result.setDefaultModel(res);
			String resultCode = res.getReturnCode()==null?"":res.getReturnCode();
			if (message.getDcblType() == BankConstants.DCBL_CORP) {
				//modified by zyt,2018-1-25，“是否做拒绝账务”为唯一判断失败的标准，其余非成功的均置进行中
				//start+++++++++++++++++++++++++
				if(CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)
						&&res.getInfo()!=null){
					if("2".equals(res.getInfo().getDealResult())
							||"3".equals(res.getInfo().getDealResult())
							||"4".equals(res.getInfo().getDealResult())){
						//响应码为000000并且交易结果为2、3、4，交易为成功
						result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
						result.setSuccess(true);
					} else {
						boolean isNeedRefund = isNeedRefund(res, base.getOrderId());
						result.setNeedRefund(isNeedRefund);
						if(isNeedRefund) {
							result.setBankRetCode(resultCode);
							result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
							result.setErrorMsg(res.getReturnMsg());
							result.setSuccess(false);
						} else {
							result.setBankRetCode(resultCode);
							result.setErrorMsg(res.getReturnMsg());
							result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
							result.setSuccess(false);
						}
					}
				} else {
					result.setBankRetCode(resultCode);
					result.setErrorMsg(res.getReturnMsg());
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
					result.setSuccess(false);
				}
				//end+++++++++++++++++++++++++
				//当响应码为0130Z110BF34
				//代表网银服务器未收到（6W8010或6W8020）的原转账交易请求,客户端可设置该请求序列号的转账交易为失败。
				//备注：响应码0130Z110BF34对应提示信息: 记录不存在
				/*if("0130Z110BF34".equals(resultCode)){
					//失败
					result.setBankRetCode(resultCode);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
	    			result.setErrorMsg(res.getInfo().getMessage());
	    			result.setSuccess(false);
				}else if(CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)
						&&res.getInfo()!=null){
					if("5".equals(res.getInfo().getDealResult())
							||"A".equals(res.getInfo().getDealResult())){
						result.setBankRetCode(resultCode);
						//响应码为000000并且交易结果为5、A时，交易为失败
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
		    			result.setErrorMsg(res.getInfo().getMessage());
		    			result.setSuccess(false);
					}else if("2".equals(res.getInfo().getDealResult())
								||"3".equals(res.getInfo().getDealResult())
								||"4".equals(res.getInfo().getDealResult())){
						//响应码为000000并且交易结果为2、3、4，交易为成功
						result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
	                	result.setSuccess(true);
					}else{
						//响应码为000000并且交易结果为0、1、6、9，交易为处理中
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
						result.setSuccess(false);
					}
				}else{
					//其他响应码均为查询失败，无法识别转账交易的处理结果，需重新查询
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
					result.setSuccess(false);
				}
				//add by zyt,2017-9-25，根据返回报文，设置是否失败，且需要做拒绝账务
				if(result.isSuccess() == false){
					result.setNeedRefund(isNeedRefund(res, base.getOrderId()));
				}*/
			} else if (message.getDcblType() == BankConstants.DCBL_PERSON) {

				//modified by zyt,2018-1-25，“是否做拒绝账务”为唯一判断失败的标准，其余非成功的均置进行中
				//start+++++++++++++++++++++++++
				if(CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)
						&&res.getInfo()!=null){
					if("4".equals(res.getInfo().getDealResult())){
						//响应码为000000并且交易结果为4，交易为成功
						result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
						result.setSuccess(true);
					} else {
						boolean isNeedRefund = isNeedRefund(res, base.getOrderId());
						result.setNeedRefund(isNeedRefund);
						if(isNeedRefund) {
							result.setBankRetCode(resultCode);
							result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
							result.setErrorMsg(res.getReturnMsg());
							result.setSuccess(false);
						} else {
							result.setBankRetCode(resultCode);
							result.setErrorMsg(res.getReturnMsg());
							result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
							result.setSuccess(false);
						}
					}
				} else {
					result.setBankRetCode(resultCode);
					result.setErrorMsg(res.getReturnMsg());
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
					result.setSuccess(false);
				}
				//end+++++++++++++++++++++++++

				/*if(CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)
						&&res.getInfo()!=null){
					if("3".equals(res.getInfo().getDealResult())
							||"A".equals(res.getInfo().getDealResult())){
						result.setBankRetCode(resultCode);
						//响应码为000000并且交易结果为3失败、A废单时，交易为失败
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
		    			result.setErrorMsg(res.getInfo().getMessage());
		    			result.setSuccess(false);
					}else if("4".equals(res.getInfo().getDealResult())){
						//响应码为000000并且交易结果为4，交易为成功
						result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
	                	result.setSuccess(true);
					}else{
						//响应码为000000并且交易结果为1复核中、2复核完成等待账务系统处理、6不确定，交易为处理中
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
						result.setSuccess(false);
					}
				}else{
					//其他响应码均为查询失败，无法识别转账交易的处理结果，需重新查询
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6066);
					result.setSuccess(false);
				}
				//add by zyt,2017-9-25，根据返回报文，设置是否失败，且需要做拒绝账务
				if(result.isSuccess() == false){
					result.setNeedRefund(isNeedRefund(res , base.getOrderId()));
				}*/
			} else {
                result.setResultCode("CcbBcdlServiceImpl.process:not match");
                return result;
            }
		} catch (GopayException e) {
			logger.error("CCB银企直连异常 query", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("CCB银企直连异常 query error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public BcdlResult queryBalance(BcdlMessage base) {
		// TODO Auto-generated method stub
		BcdlResult result = new BcdlResult();
		try {
			BcdlMessage message = (BcdlMessage) base;
			TransResQueryBalanceBody res = ccbBcdlManager.queryBal(message);
			result.setDefaultModel(res);
			String resultCode = res.getReturnCode()==null?"":res.getReturnCode();
			if(CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)){
				result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
	        	result.setModel("payAccNum", res.getPayAccNum());
                result.setModel("balance", res.getInfo().getBalance());
	        	result.setSuccess(true);
			}else {
				result.setBankRetCode(resultCode);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6027);
				result.setErrorMsg(res.getReturnMsg());
				result.setSuccess(false);
			}
		} catch (GopayException e) {
			logger.error("CCB银企直连异常 query bal", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception ex){
			logger.error("CCB银企直连异常 query bal error", ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public BcdlResult sendBankQueryBalance(BcdlMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BcdlResult eftRetry(BcdlMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public BcdlResult sendBankPacket(BcdlPacket bcdlPacket) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BcdlPacketRes queryPacket(BcdlPacket bcdlPacket) {



        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BcdlResult queryAcctDetail(BcdlMessage base) {
		{
			BcdlResult result = new BcdlResult();
			try {
				base.setLabel("QUERY_1");
				TransResQueryBody6WY101 res= ccbBcdlManager.queryAcctDetail(base);
				result.setDefaultModel(res);
				String resultCode = res.getReturnCode()==null?"":res.getReturnCode();
				if(CcbConstants.BCDL_RESULT_CODE_SUCC.equals(resultCode)){
					result.setResultCode(ProcCodeConstants.PROC_CODE_100S1000);
					result.setErrorMsg("业务系统交易查询成功");
					result.setSuccess(true);
				}else {
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E5062);
					result.setErrorMsg(res.getReturnMsg());
					result.setSuccess(false);
				}
			} catch (GopayException e) {
				logger.error("CCB DCC银企直连查询异常 queryAcctDetail", e);
				result.setResultCode(e.getErrCode());
				result.setSuccess(false);
			} catch (Exception ex){
				logger.error("CCB DCC 银企直连异常 queryAcctDetail  error", ex);
				result.setSuccess(false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			}
			return result;
		}
    }

}
